package token

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

var jwtkey = []byte("www.topgoer.com")
var str string

type Claims struct {
	UserId string `json:"foo"`
	jwt.StandardClaims
}

func init() {
	r := gin.Default()
	r.GET("/set", setting)
	r.GET("/get", getting)
	r.Run(":8080")
}

func setting(context *gin.Context) {
	expireTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		"bar",
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "127.0.0.1",
			Subject:   "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtkey)
	fmt.Printf("%v", tokenString)
	if err != nil {
		fmt.Println(err)
	}
	str = tokenString
	context.JSON(200, gin.H{
		"token": tokenString,
	})
}

func getting(context *gin.Context) {
	//tokenString := context.GetHeader("Authorization")
	if str == "" {
		context.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "权限不足",
		})
		context.Abort()
		return
	}

	token, claims, err := ParseToken(str)
	if err != nil || !token.Valid {
		context.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "权限不足",
		})
	} else {
		context.JSON(200, gin.H{
			"message": "验证成功",
		})
	}
	fmt.Println(claims.UserId)
}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	Claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtkey, nil
	})
	return token, Claims, err
}
